import base64

import requests
from openai import OpenAI

base_url = "http://localhost:8000/v1/"

hy_source = "web"
hy_user = "702c60194c5b49089020f266186e7f6d"    # 替换为你的用户ID
hy_token = "9D9toucekxl86Jx/J0nqh37i8kkQzkQPmv28FjZgKbW0JVJ2l0Ir6wtYF57Xzazgn9XxJYh46Z0A7QgS6VtB3w=="   # 替换为你的token

agent_id = "naQivTmsDa"
chat_id = ""    # 可选，如果不提供会自动创建

# upload，可选
url = base_url + "upload"

# file_name = "example1.png"
# with open(file_name, "rb") as f:
#     file_data = base64.b64encode(f.read()).decode("utf-8")
# data = {
#     "agent_id": agent_id,
#     "hy_source": hy_source,
#     "hy_user": hy_user,
#     "file": {
#         "file_name": file_name,
#         "file_data": file_data ,
#         "file_type": "image",   # 只能是 image 或 doc
#     },
# }
# headers = {"Authorization": f"Bearer {hy_token}"}
# response = requests.post(url, json=data, headers=headers)
# if response.status_code == 200:
#     print("File uploaded successfully:", response.json())
#     multimedia = [response.json()]
# else:
#     print("File upload failed:", response.status_code, response.text)
#     multimedia = []
# print(multimedia)

# create chat_id
url = base_url + "chat/conversation/create"

headers = {"Authorization": f"Bearer {hy_token}"}
data = {
    "hy_source": hy_source,
    "hy_user": hy_user,
    "agent_id": agent_id,
}
try:
    response = requests.post(url, json=data, headers=headers)
    if response.status_code == 200:
        print("create chatId successfully:", response.json())
        chat_id = response.json().get("chat_id", "")
    else:
        print("create chatId failed:", response.status_code, response.text)
        chat_id = ""
except Exception as e:
    print("Request exception:", e)
    chat_id = ""
print(chat_id)

# chat
client = OpenAI(base_url=base_url, api_key=hy_token)

response = client.chat.completions.create(
    model="deepseek-r1",
    messages=[{"role": "user", "content": "好烦啊！真的"}],
    stream=True,
    extra_body={
        "hy_source": hy_source,
        "hy_user": hy_user,
        "agent_id": agent_id,
        "chat_id": chat_id,
        "should_remove_conversation": False,
        # "multimedia": multimedia,
    },
)

for chunk in response:
    print(chunk.choices[0].delta.content or "")